//
//  WXRefreshControl.swift
//  weibo
//
//  Created by 王旭 on 16/4/23.
//  Copyright © 2016年 王旭. All rights reserved.


//自定义下拉刷新按钮

import UIKit

//刷新控件状态
enum WXRefreshControlState:Int {
    case Normal = 0     //普通状态,包括没有拖拽完全
    case Pulling = 1    //已经完全拖拽状态,松手就会刷新数据
    case Refreshing = 2 //数据刷新状态
}

//刷新控件高度
let WXRefreshControlH :CGFloat = 50

class WXRefreshControl: UIControl {
    
    //父控件
    private var tableView : UIScrollView?
    //控件状态
    private var controlState :WXRefreshControlState = .Normal{
        didSet{
            switch controlState{
            case .Normal:
                //菊花停转
                activityIndicatorView.stopAnimating()
                //箭头朝下
                arrowImageView.highlighted = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImageView.transform = CGAffineTransformIdentity
                })
                //文字
                noticeLabel.text = "下拉刷新"
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25) { () -> Void in
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - WXRefreshControlH
                    }
                }
            case .Pulling:
                //箭头向上
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                //文字
                noticeLabel.text = "松手刷新"
            case .Refreshing:
                //隐藏箭头
                arrowImageView.hidden = true
                //菊花转
                activityIndicatorView.startAnimating()
                //文本
                noticeLabel.text = "正在刷新"
                //tableView上移动
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.tableView?.contentInset.top = self.tableView!.contentInset.top + WXRefreshControlH
                })
                //调用刷新
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //界面布局
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//界面布局
    func setupUI() {
        //背景色
       backgroundColor = UIColor.redColor()
        //设置高度
        self.frame.size.height = WXRefreshControlH
        //设置x点
//        self.frame.origin.x = 0
        //设置y点
        self.frame.origin.y = -WXRefreshControlH
        
        //添加控件

        addSubview(arrowImageView)
        addSubview(noticeLabel)
        addSubview(activityIndicatorView)
        //约束

        arrowImageView.snp_makeConstraints { (make) -> Void in

            make.centerY.equalTo(self).offset(-35)
            make.centerX.equalTo(self)
        }
        noticeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(arrowImageView)
            make.leading.equalTo(arrowImageView.snp_trailing)
        }
        activityIndicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView)
        }
        
    }
//停止刷新的方法
    func endRefreshing() {
        controlState = .Normal
    }
    
//添加到父控件时调用的方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //取到父控件
        guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else {
            return
        }
        //关联属性
        self.tableView = tableView as? UIScrollView
        //设置宽度
        self.frame.size.width = tableView.frame.width
        
        //KVO
        tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
    }
    
//KVO检测的键值变化
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //获得偏移量
        let contentOffset = self.tableView!.contentOffset
//        print(contentOffset.y)
        
        let value = -tableView!.contentInset.top - WXRefreshControlH
        
        //根据偏移量判断下拉控件在何种状态
        if tableView!.dragging {
            if contentOffset.y >= value {
               //没有完全显示
                controlState = .Normal
                print("没有完全显示")
            }else{
                if contentOffset.y < value && controlState == .Normal{
                //完全显示状态
                controlState = .Pulling
                print("完全显示状态")
                }
            }
        }else{

            if controlState == .Pulling{
                //松手刷新
                controlState = .Refreshing
                print("松手刷新")

            }
        }
        
//        if tableView!.dragging {
//            if contentOffset.y < value && controlState == .Normal{
//                print("完全显示")
//                controlState = .Pulling
//            }else{
//                if contentOffset.y >= value && controlState == .Pulling{
//                    print("未完全显示")
//                    controlState = .Normal
//                }
//            }
//        }else{
//            if controlState == .Pulling{
//                print("释放刷新")
//                controlState = .Refreshing
//            }
//        }
    }
    
//移除KVO
    deinit {
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
//懒加载控件
    //菊花
    private lazy var activityIndicatorView :UIActivityIndicatorView = UIActivityIndicatorView()
    //箭头
    private lazy var arrowImageView :UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文本Label
    private lazy var noticeLabel :UILabel = UILabel(textColor: UIColor.blackColor(), fontSize: 14)

    
}
